package com.situ.crm2026.api;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.situ.crm2026.model.MemberCourseReservation;
import com.situ.crm2026.model.dto.ReservationDto;
import com.situ.crm2026.service.MemberCourseReservationService;
import com.situ.crm2026.util.JsonResult;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping(value = "/api/v1/reservations", produces = MediaType.APPLICATION_JSON_VALUE)
public class ReservationApi {

    private MemberCourseReservationService reservationService;

    @Autowired
    public void setReservationService(MemberCourseReservationService reservationService) {
        this.reservationService = reservationService;
    }

    @GetMapping
    public ResponseEntity<JsonResult<?>> findAll(@RequestParam (defaultValue = "1") Integer pageNo,
                                                 @RequestParam (defaultValue = "10") Integer pageSize){
        Page<ReservationDto> page = new Page<>(pageNo, pageSize);
        page = reservationService.findAllWithDetails(page);
        return ResponseEntity.ok(JsonResult.success(page));
    }
    @PostMapping("/reserve")
    public ResponseEntity<JsonResult<?>> reserve(@RequestBody MemberCourseReservation reservation) {
        //时间冲突逻辑！！！！！
        if(reservationService.hasTimeConflict(reservation.getMemberId(), reservation.getCourseId())){
            return ResponseEntity.ok(JsonResult.fail("该时间段有课程冲突"));
        }

        boolean success = reservationService.reserve(reservation.getMemberId(), reservation.getCourseId(),
                reservation.getStatus(),reservation.getCourseType());
        if (success) {
            return ResponseEntity.ok(JsonResult.success("预约成功"));
        } else {
            return ResponseEntity.ok(JsonResult.fail("预约失败，可能已存在"));
        }
    }

    @PutMapping("/confirm/{id}")
    public ResponseEntity<JsonResult<?>> confirm(@PathVariable Integer id) {
        boolean success = reservationService.confirm(id);
        if (success) {
            return ResponseEntity.ok(JsonResult.success("确认成功"));
        } else {
            return ResponseEntity.ok(JsonResult.fail("确认失败"));
        }
    }

    @DeleteMapping("/cancel/{id}")
    public ResponseEntity<JsonResult<?>> cancel(@PathVariable Integer id,
                                                HttpServletRequest request) {
        // 这里可以增加权限验证，确保用户只能取消自己的预约
        boolean success = reservationService.cancel(id);
        if (success) {
            return ResponseEntity.ok(JsonResult.success("取消成功"));
        } else {
            return ResponseEntity.ok(JsonResult.fail("取消失败"));
        }

    }


}
